﻿using System;
using ContactManager.Common;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace ContactManager
{
    public partial class LogFrm : AlSkin.AlForm.AlBaseForm
    {
        private int id = 0;

        //上次内容，用于判断修改
        private string lastContent = "";

        public LogFrm()
        {
            InitializeComponent();
        }

        private void LogFrm_Load(object sender, EventArgs e)
        {
            //初始化最近联系人
            this.combRecent.Items.Clear();
            string recentSql = "select top 18 c.c_id,c.c_name,max(t.t_time) from contacters c,traces t where c.c_id = t.t_c_id group by c.c_id,c.c_name order by max(t.t_time) desc";
            DataSet recentDs = AccessHelper.ExecuteQuery(recentSql);
            foreach (DataRow dr in recentDs.Tables[0].Rows)
            {
                ComboBoxItem ci = new ComboBoxItem();
                ci.Text = Convert.ToString(dr["c_name"]);
                ci.Value = dr["c_id"];
                this.combRecent.Items.Add(ci);
            }
            
            this.labelContactName.Text = Constant.TITLE + GlobleUser.USER_NAME;
            setMonthBold();
            getDaily(this.monthCalendarMain.TodayDate);
        }

        private void setMonthBold()
        {
            //设置当前月的所有日记
            DateTime calendarDate = this.monthCalendarMain.SelectionStart;
            DateTime startDate = new DateTime(calendarDate.Year, calendarDate.Month, 1);
            DateTime endDate = startDate.AddMonths(1).AddDays(-1);
            string sql = "select * from daily where d_time >=#" + startDate.ToString("yyyy/MM/dd") + "# and d_time <=#" + endDate.ToString("yyyy/MM/dd") + "#";
            //Console.WriteLine(startDate.ToString("yyyy/MM/dd") + " " + endDate.ToString("yyyy/MM/dd"));

            DataSet ds = AccessHelper.ExecuteQuery(sql);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                DateTime dTime = Convert.ToDateTime(dr["d_time"].ToString());
                this.monthCalendarMain.AddBoldedDate(dTime);
            }
            this.monthCalendarMain.UpdateBoldedDates();

        }

        private void monthCalendarMain_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
        {
            setMonthBold();
        }

        private void LogFrm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("您确定要退出，并保存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
            {
                this.btnSave_Click(this, null);
                HomeFrm.lf = null;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void monthCalendarMain_DateSelected(object sender, DateRangeEventArgs e)
        {
            getDaily(e.Start);
        }

        private void getDaily(DateTime dt)
        {
            //查数据
            DateTime selectDate = dt;
            string sql = "select * from daily where d_time =#" + selectDate.ToString("yyyy/MM/dd") + "#";
            DataSet ds = AccessHelper.ExecuteQuery(sql);
            //初始化控件
            this.id = 0;
            this.textBoxMain.Clear();
            this.comboBoxWeather.Text = "";
            ChineseCalendar cc = new ChineseCalendar(selectDate);
            this.labDate.Text = "日期：" + selectDate.ToString("yyyy年MM月dd日") + "  " + cc.ChineseDateString + " " + selectDate.ToString("dddd");
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                this.textBoxMain.Text = dr["d_text"].ToString();
                this.id = Convert.ToInt32(dr["d_id"].ToString());
                this.comboBoxWeather.Text = dr["d_weather"].ToString();

                this.lastContent = this.textBoxMain.Text;
            }

            this.textBoxMain.Focus();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string text = this.textBoxMain.Text.Trim();
            string weather = this.comboBoxWeather.Text.Trim();
            string date = this.monthCalendarMain.SelectionStart.ToString("yyyy/MM/dd");

            if (text.Length > 0 || weather.Length > 0)
            {
                if (id == 0)
                {
                    string addSql = "insert into daily(d_time,d_text,d_weather) values(#" + date + "#,?,?)";
                    OleDbParameter[] ps = {
                                        new OleDbParameter("@d_text",text),
                                        new OleDbParameter("@d_weather",weather)
                                      };
                    int idTemp = AccessHelper.ExecuteInsert(addSql, ps);
                    if (idTemp > 0)
                    {
                        MessageBox.Show("保存成功");
                        this.id = idTemp;
                        this.lastContent = this.textBoxMain.Text.Trim();
                    }
                }
                else
                {
                    if (!text.Equals(lastContent) && lastContent.Length > 0)
                    {
                        string uSql = "update daily set d_time=#" + date + "#,d_text=?,d_weather=? where d_id=?";
                        OleDbParameter[] ps = {
                                        new OleDbParameter("@d_text",text),
                                        new OleDbParameter("@d_weather",weather),
                                        new OleDbParameter("@d_id",id)
                                      };
                        if (AccessHelper.ExecuteNonQuery(uSql, ps) > 0)
                        {
                            MessageBox.Show("修改成功");
                            this.lastContent = this.textBoxMain.Text.Trim();
                        }
                    }
                    
                }
            }
            
        }

        private void combRecent_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBoxItem recent = (ComboBoxItem)this.combRecent.SelectedItem;
            TracesForm tf = new TracesForm(recent.Value.ToString());
            tf.ShowDialog();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                //打开文件
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "导出txt (*.txt)|*.txt";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.Title = "导出文件保存路径";
                saveFileDialog.ShowDialog();
                string strName = saveFileDialog.FileName;

                if (strName != null)
                {
                    //打开流
                    FileStream fout = new FileStream(strName, FileMode.Create, FileAccess.Write);
                    StreamWriter brout = new StreamWriter(fout, Encoding.Default);

                    //读数据
                    string sql = "select * from daily";
                    DataSet ds = AccessHelper.ExecuteQuery(sql);

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        DateTime selectDate = Convert.ToDateTime(dr["d_time"].ToString());
                        ChineseCalendar cc = new ChineseCalendar(selectDate);
                        brout.WriteLine("日期：" + selectDate.ToString("yyyy年MM月dd日") + "  " + cc.ChineseDateString + " " + selectDate.ToString("dddd") + "   天气：" + dr["d_weather"].ToString());
                        brout.WriteLine(dr["d_text"].ToString());
                        brout.WriteLine();
                        brout.WriteLine();
                        brout.WriteLine();
                    }

                    brout.Flush();
                    brout.Close();
                    MessageBox.Show("导出完毕");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "出错内容");
            }
            
        }

        private void monthCalendarMain_MouseDown(object sender, MouseEventArgs e)
        {
            this.textBoxMain.Clear();
            this.lastContent = "";
        }

    }
}
